import {
  Card,
  Breadcrumb,
  Form,
  Input,
  Button,
  Radio,
  Upload,
  message
} from 'antd'
import styles from './index.module.scss'
import { Link, useHistory, useParams } from 'react-router-dom'
import Channels from '@/components/Channels'
import { PlusOutlined } from '@ant-design/icons'
import ReactQuill from 'react-quill'
import 'react-quill/dist/quill.snow.css'
import { useState, useEffect } from 'react'
import { addArticle, getArticleInfo, editArticle } from '@/api'

function Publish () {
  const history = useHistory()
  // 接收编辑文章的id
  const params = useParams()
  const [form] = Form.useForm()
  // 图片上传列表
  const [fileList, setFileList] = useState([])
  // 图片上传列表备份
  const [temFileList, setTemFileList] = useState([])
  // 图片最大上传张数
  const [max, setMax] = useState(1)
  // 图片上传
  const uploadChange = info => {
    const res = info.fileList.map(i => {
      if (i.response) {
        return {
          url: i.response.data.url
        }
      } else {
        return i
      }
    })
    setFileList(res)
    setTemFileList(res)
  }
  // 单选框改变
  const radioChange = e => {
    const _max = e.target.value
    setMax(_max)
    const _fileList = [...temFileList].splice(0, _max)
    setFileList(_fileList)
  }
  // 文章提交
  const submit = async (values, bol) => {
    const cover = {
      type: max,
      images: fileList.map(i => i.url)
    }
    const data = { ...values, cover }
    if (params.id) {
      // 编辑文章
      await editArticle({ ...data, id: params.id }, bol)
    } else {
      // 新增文章
      await addArticle(data, bol)
    }
    history.push('/home/article')
  }
  // 发布文章
  const onFinish = values => {
    submit(values, false)
    message.success(`${params.id ? '编辑' : '发布'}文章成功`)
  }
  // 存为草稿
  const saveDraft = async () => {
    const res = await form.validateFields()
    submit(res, true)
    message.success('存为草稿成功')
  }
  // 编辑文章时获取文章信息
  useEffect(() => {
    if (!params.id) return
    async function getData () {
      const res = await getArticleInfo(params.id)
      const { cover, ...otherValue } = res.data
      form.setFieldsValue(otherValue)
      setMax(cover.type)
      const _fileList = cover.images.map(i => {
        return { url: i }
      })
      setFileList(_fileList)
      setTemFileList(_fileList)
    }
    getData()
  }, [])

  return (
    <div className={styles.publish}>
      <Card
        title={
          <Breadcrumb>
            <Breadcrumb.Item>
              <Link to='/home'>首页</Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>{params.id ? '编辑' : '发布'}文章</Breadcrumb.Item>
          </Breadcrumb>
        }
      >
        <Form
          form={form}
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 20 }}
          initialValues={{ content: '' }}
          onFinish={onFinish}
          autoComplete='off'
        >
          <Form.Item
            label='标题'
            name='title'
            wrapperCol={{ span: 6 }}
            rules={[{ required: true, message: '标题不能为空!' }]}
          >
            <Input placeholder='请输入文章的标题' />
          </Form.Item>
          <Form.Item
            label='频道'
            name='channel_id'
            wrapperCol={{ span: 6 }}
            rules={[{ required: true, message: '频道不能为空!' }]}
          >
            <Channels />
          </Form.Item>
          <Form.Item label='封面' wrapperCol={{ span: 6 }}>
            <Radio.Group value={max} onChange={radioChange}>
              <Radio value={1}>单图</Radio>
              <Radio value={3}>三图</Radio>
              <Radio value={0}>无图</Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item wrapperCol={{ offset: 4 }}>
            <Upload
              name='image'
              fileList={fileList}
              listType='picture-card'
              action='http://geek.itheima.net/v1_0/upload'
              onChange={uploadChange}
            >
              {fileList.length < max && <PlusOutlined />}
            </Upload>
          </Form.Item>
          <Form.Item
            label='内容'
            name='content'
            rules={[{ required: true, message: '内容不能为空!' }]}
          >
            <ReactQuill placeholder='请输入文章的内容' />
          </Form.Item>
          <Form.Item wrapperCol={{ offset: 4 }}>
            <Button type='primary' size='large' htmlType='submit'>
              {params.id ? '编辑' : '发布'}文章
            </Button>
            &nbsp;&nbsp;
            <Button size='large' onClick={saveDraft}>
              存为草稿
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </div>
  )
}

export default Publish
